package com.example.robootttsdemo

import android.content.Context
import android.speech.tts.TextToSpeech
import java.util.*

/**
 * tts 文字转语音进行播放 系统的 不支持的话安装一个讯飞语音引擎
 * @author: tjf
 * @date: 2022-11-07
 * @desc：
 */
class SpeechUtils(context: Context?) {

    private var textToSpeech // TTS对象
            : TextToSpeech? = null

    companion object {
        private var singleton: SpeechUtils? = null
        fun getInstance(context: Context?): SpeechUtils? {
            if (singleton == null) {
                synchronized(SpeechUtils::class.java) {
                    if (singleton == null) {
                        singleton = SpeechUtils(context)
                    }
                }
            }
            return singleton
        }
    }


    init {
        textToSpeech = TextToSpeech(context) { i ->
            if (i == TextToSpeech.SUCCESS) {
                textToSpeech!!.language = Locale.CHINA
                textToSpeech!!.setPitch(2.5f) // 设置音调，值越大声音越尖（女生），值越小则变成男声,1.0是常规
                textToSpeech!!.setSpeechRate(0.5f)
            }
        }
    }


    fun speakText(text: String?) {
        if (textToSpeech != null) {
            textToSpeech!!.speak(
                text,
                TextToSpeech.QUEUE_FLUSH, null
            )
        }
    }

    fun onStop() {
        if (textToSpeech != null) {
            // 不管是否正在朗读TTS都被打断
            textToSpeech!!.stop()
            // 关闭，释放资源
            textToSpeech!!.shutdown()
        }
    }


    fun onDestroy() {
        if (textToSpeech != null) {
            onStop()
            textToSpeech = null
        }
    }
}